package com.handle.system.web.controller;

import com.handle.common.core.constants.Constant;
import com.handle.common.core.result.JsonResult;
import com.handle.common.redis.util.RedissonUtil;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangqing
 * @version V1.0
 * @description 验证码
 * @date 9/3/2021 10:27 AM
 */
@RestController
@RequestMapping("/captcha")
@AllArgsConstructor
@Api(tags = "CaptchaController", value = "验证码控制层")
public class CaptchaController {

    private final RedissonUtil redissonUtil;
    private final RedissonClient redissonClient;
    private final DistributedLock distributedLock;


    @ApiOperation("获取图片验证码")
    @ResponseBody
    @GetMapping("/images")
    public JsonResult captcha(String id) {
//        String key="mytest";
//        String uid = UUID.randomUUID().toString();
//        Long lock = distributedLock.lock(key, uid, "10");
//        try {
//            if(lock==1){
//                Thread.sleep(30*1000);
//                System.out.println("我醒了");
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            distributedLock.unlock(key,uid);
//        }
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        // 运算位数
        captcha.setLen(2);
        // 生成验证码结果
        String capText = captcha.text();
        // 保存验证码信息
        String randomStr = UUID.randomUUID().toString().replaceAll("-", "");
        redissonClient.getBucket(Constant.DEFAULT_CODE_KEY + randomStr).set(capText,5, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>(16);
        map.put("randomStr",randomStr);
        map.put("image",captcha.toBase64());
        // 将key和base64返回给前端
        return JsonResult.success(map);

//        RLock lock = redissonClient.getLock(id);
//        if(lock.tryLock()){
//            try {
//                Thread.sleep(10000);
//                System.out.println("执行业务逻辑");
//            }catch (Exception e){
//                e.getMessage();
//            }finally {
//                lock.unlock();
//            }
//        }else {
//            System.out.println("没有获取到锁");
//        }
//        return ResultUtil.success();
    }


}
